<template>
    <div class="form-container">
        <h2>注册</h2>
        <form @submit.prevent="handleRegister">
            <input type="phone" v-model="user.phone" placeholder="手机号" required />
            <input type="password" v-model="user.password" placeholder="密码" required />
            <input type="password" v-model="confirmPassword" placeholder="确认密码" required />
            <div class="tip">
                <router-link to="/login" class="login-link">已有账号?</router-link>
            </div>
            <button type="submit">注册</button>
            <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
        </form>
    </div>
</template>

<script setup>
import { ref } from "vue";
import useUser from "@/hooks/useUser.js";
const { user, register } = useUser();

const confirmPassword = ref("");
const errorMessage = ref("");

const handleRegister = () => {
    if (user.value.phone.length !== 11) {
        errorMessage.value = "手机号必须是11位数字";
        return;
    }

    if (user.value.password !== confirmPassword.value) {
        errorMessage.value = "两次密码输入不一致，请重新输入";
        return;
    }

    errorMessage.value = "";
    register();
};
</script>

<style scoped>
.form-container {
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    width: 300px;
    margin: 0 auto;
    margin-top: 200px;
}

h2 {
    margin-bottom: 20px;
    text-align: center;
}

input {
    width: 100%;
    padding-top: 12px;
    padding-bottom: 12px;
    margin: 10px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    width: 101%;
    padding: 10px;
    margin: 1px;
    border: none;
    border-radius: 5px;
    color: white;
    font-size: 16px;
    cursor: pointer;
    text-align: center;
}

button {
    background-color: #5aa39a;
}

button:hover {
    background-color: #218838;
}

.tip {
    text-align: right;
    margin: 10px 0;
}

.login-link {
    color: #5aa39a;
    text-decoration: none;
}

.login-link:hover {
    text-decoration: underline;
}

.error {
    color: red;
    font-size: 14px;
    text-align: center;
    margin-top: 10px;
}
</style>